package com.yswy.backstage.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.domain.entity.user.Permission;
import com.yswy.domain.entity.user.RolePermission;
import com.yswy.domain.entity.user.User;
import com.yswy.domain.entity.user.UserRole;
import com.yswy.domain.mapper.user.PermissionMapper;
import com.yswy.domain.mapper.user.RolePermissionMapper;
import com.yswy.domain.mapper.user.UserMapper;
import com.yswy.domain.mapper.user.UserRoleMapper;
import com.yswy.backstage.param.UserPARAM;
import com.yswy.backstage.service.SsoService;
import com.yswy.common.enums.ResultStatus;
import com.yswy.common.model.ResultModel;
import com.yswy.common.utils.AES128Util;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * This is Description
 *
 * @author linlifu
 * @date 2020/01/07
 */
@Slf4j
@Service
public class SsoServiceImpl extends ServiceImpl<UserMapper, User> implements SsoService {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public ResultModel login(UserPARAM req) {
        User user = getOne(Wrappers.<User>lambdaQuery().eq(User::getUserPhone, req.getUserPhone()));
        Assert.notNull(user, "请检查账号");
        Assert.isTrue(!user.getFreezingSatus(),"账号已被封禁，无法登陆");
        String encrypt = "";
        try {
            encrypt = AES128Util.encrypt(req.getPwd());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Assert.isTrue(encrypt.equals(user.getPwd()), "密码错误");
        if (user.getUserName().equals("root")) {
            return ResultModel.ok(user);
        }

        if (isAdmin( user)){
            user.setIsAdmin(1);
        }else {
            user.setIsAdmin(0);
        }
        //更新用户的 AuthToken
        renewUserLoginAuthToken(user);
        return ResultModel.ok(user);
    }




    @Override
    public Boolean isAdmin(User user){
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        for (UserRole userRole : userRoles) {
            if (null != userRole.getRoleType() && userRole.getRoleType() == 1) {
                return true;
            }
        }
        return false ;
    }

    @Override
    public Long isAdminToUserId(User user) {
        Long userId = user.getId().longValue();
        if (isAdmin(user)){
            userId = null;
        }
        return userId ;
    }


    private void renewUserLoginAuthToken(User user) {
//        log.info("为用户生成新的授权码");
        user.setAuthToken(getNewUserAuthToken());
        user.setExpireTime(new LocalDateTime().plusMonths(12).toDate());
        Assert.isTrue(saveOrUpdate(user), "登录失败");
    }

    private String getNewUserAuthToken() {
        return UUID.randomUUID().toString();
    }

    @Override
    public ResultModel logout(User user) {
//        User u = getById(user.getId());
//        Assert.notNull(user, "未找到该用户");
        if (user.getUserName().equals("root")) {
            return ResultModel.ok(ResultStatus.LOGOUT_SUCCESS);
        }
        user.setAuthToken(getNewUserAuthToken());
        user.setExpireTime(new Date());
        Assert.isTrue(saveOrUpdate(user), "注销失败");
        return ResultModel.ok(ResultStatus.LOGOUT_SUCCESS);
    }

    @Override
    public User getUserByAuthToken(String authToken) {
        if ("root".equals(authToken)) {
            return list(new LambdaQueryWrapper<User>().eq(User::getUserName, authToken)).get(0);
        }
        User user = getOne(new QueryWrapper<User>().lambda()
                .eq(User::getAuthToken, authToken));
        if (user != null) {
            user.setExpireTime(new LocalDateTime().plusMonths(12).toDate());
            if (!updateById(user)) {
                return null;
            }
        }
        return user;

    }

    @Override
    public Map<String, Long> getAllModelPermission() {
        List<Permission> permissionList = permissionMapper.selectList(new QueryWrapper<Permission>().lambda().eq(Permission::getIsDel, 0).eq(Permission::getFreezingSatus, false));
        permissionList = permissionList.stream().filter(f -> Arrays.asList(1, 2, 4).contains(f.getPermissionType())).peek(p -> {
            p.setName(p.getPermissionType() == 2 && p.getComponent().contains("/") ? p.getComponent() : p.getPath());
        }).collect(Collectors.toList());
        return permissionList.stream().collect(Collectors.toMap(Permission::getName, Permission::getId));
    }

    @Override
    public Set<Integer> getPermissionMapByUser(User user) {
        Set<Integer> set = new HashSet<>();
        //获取此人所有角色
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().lambda()
                .eq(UserRole::getUserId, user.getId()));
        Assert.notNull(userRoles, "获取此人所有角色失败");
        //获取此人所有权限
        for (UserRole userRole : userRoles) {
            List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().lambda()
                    .eq(RolePermission::getRoleId, userRole.getRoleId()));
            rolePermissionList.stream().forEach(rolePermission -> {
                set.add(rolePermission.getPermissionId());
            });
        }
        return set;
    }
}
